package com.byzoro.exception;

import com.byzoro.utils.RestfulMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
@Slf4j
public class ExceptionHandlers {
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Map<String, Object> handleException (Exception e) {
        Map<String, Object> err = new HashMap<>();
        //捕获404异常
        if (e instanceof NoHandlerFoundException) {
            err.put("code", 404);
            err.put("message", RestfulMessage.NotFound);
        } else {
            log.error("server error {e}", e);
            err.put("code", 500);
            err.put("message", RestfulMessage.ServerError);
        }
        return err;
    }
}
